//
//  ShoppingCarController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/7/21.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

protocol ShoppingCarCellDelegate : NSObjectProtocol {
    
    func calculateTotalPrice()
    
}

class ShoppingCarController: BaseViewController {
    
    
    var shopCartList = [ShopCartListModel]()
    
    var hotRecommList = [HomeItemModel]()
    
    lazy var likeItems : [[HomeItemModel]] = {
        
        var arrayM = [[HomeItemModel]]()
        var subArrayM : [HomeItemModel]?
        
        for (index,value) in self.hotRecommList.enumerated() {
            
            value.goods_image = value.goods_image_url
            
            if index % 2 == 0 {
                
                subArrayM = [HomeItemModel]()
                
                subArrayM?.append(value)
                
                
            }else{
                
                subArrayM?.append(value)
                
                arrayM.append(subArrayM!)
                
                
            }
            
            
        }
        
        
        if self.hotRecommList.count % 2 == 1 {
            
            subArrayM = [HomeItemModel]()
            
            let temp = self.hotRecommList.last!
            
            temp.goods_image = temp.goods_image_url

            subArrayM?.append(temp)
            
            arrayM.append(subArrayM!)
            
        }
        
        
        
        return arrayM
        
        
    }()
    

    
    
    var isTapDisappear = false
    
    lazy var bottomView : ShoppingCarBottomView = {
        
        let temp = Bundle.main.loadNibNamed(self.StringFromClass(classType: ShoppingCarBottomView.self), owner: nil, options: nil)?.first as! ShoppingCarBottomView
        
        temp.isHidden = true
        
        temp.delegate = self
        
        self.view.addSubview(temp)
        
        
        return temp
        
    }()
    
    
    lazy var nothingRootView : NoLoginLogoView = {
        
        let temp = Bundle.main.loadNibNamed(self.StringFromClass(classType: NoLoginLogoView.self), owner: nil, options: nil)?.first as! NoLoginLogoView
        
        temp.isHidden = true
        
        temp.frame = UIScreen.main.bounds
        
        self.view.addSubview(temp)
        
        
        return temp
        
    }()


    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        isTapDisappear = false

        
        if UserViewModel.shared.userIsLogin() == false {
            
            nothingRootView.isHidden = false
            
            nothingRootView.bottomLabel.attributedText = attributedString(str: "亲!您还未登录哦~\n点击登录", font: UIFont.systemFont(ofSize: 15))
            
            
            return
            
        }else{
            
            nothingRootView.isHidden = true

            loadData()
            
        }

        
    }
    
    
    
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
        
        if isTapDisappear == false {
            
            if UserViewModel.shared.userIsLogin() == true {
                
                uploadShoppingCar()
            }
            
        }
    
    
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        plainTableView.rowHeight = UITableViewAutomaticDimension
        
        plainTableView.estimatedRowHeight = 100
        
        plainTableView.separatorStyle = .none
        
        plainTableView.backgroundColor = UIColor.viewBgGrey()
        
        plainTableView.register(BaseTableViewCell.self, forCellReuseIdentifier: BaseTableViewCell.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: ShoppingCarHeaderOne.self), bundle: nil), forHeaderFooterViewReuseIdentifier: ShoppingCarHeaderOne.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: ShoppingCarHeaderTwo.self), bundle: nil), forHeaderFooterViewReuseIdentifier: ShoppingCarHeaderTwo.identifer())



        plainTableView.register(UINib(nibName: StringFromClass(classType: ShoppingCarCell.self), bundle: nil), forCellReuseIdentifier: ShoppingCarCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: ShoppingNotingCell.self), bundle: nil), forCellReuseIdentifier: ShoppingNotingCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: HomeYouLikeCell.self), bundle: nil), forCellReuseIdentifier: HomeYouLikeCell.identifer())
        
        
        if navigationItem.title == "购物车" {
            bottomView.frame = CGRect(x: 0, y: KScreenH - 98, width: KScreenW, height: 49)
            
        } else {
            
            navigationItem.title = "购物车"
            
            bottomView.frame = CGRect(x: 0, y: KScreenH - 49, width: KScreenW, height: 49)
            
        }


    }
    
    
    
    
    func attributedString(str: String, font: UIFont) -> NSAttributedString? {
        
        //编写规则登录
        let patten = "[点][击][登][录]"
        //创建正则表达式对象
        
        //caseInsensitive  忽略大小写  最常用
        //dotMatchesLineSeparators 允许 . 匹配任意字符，包括回车换行
        let regex = try! NSRegularExpression(pattern: patten, options: NSRegularExpression.Options.caseInsensitive)
        
        //根据规则匹配指定字符串中第一个符合规则的字符串，并且返回一个NSTextCheckingResult
        let res = regex.firstMatch(in: str, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range:  NSRange(location: 0, length: str.characters.count))
        
        
        // 根据原有字符串生成属性字符串
        let strM = NSMutableAttributedString(string: str)
        
        strM.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, str.characters.count))
        
        strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.dakGray(), range: NSMakeRange(0, str.characters.count))
        
        
        
        let paragr = NSMutableParagraphStyle.init()
        
        paragr.lineSpacing = 5;
        
        paragr.alignment = .center
        
        strM.addAttribute(NSParagraphStyleAttributeName, value: paragr, range: NSMakeRange(0, str.characters.count))
        

        
        if let temp = res?.range {
            
            strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: temp)
            
            strM.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 19), range: temp)
            
        }
        
        return strM
        
        
        
        
    }
    
    
    func uploadShoppingCar() {
        
        var temp = getCarInfoStr2()
        
        if temp == nil {
            
            temp = ""
        }
            var parmeter  = [String : AnyObject]()
            
            parmeter["cart_info"] = temp! as AnyObject
            
            
            NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_cart&a=update_all_cart", parameters: parmeter, completionHandler: { (_, _) in
                
                
            })
            

            
        
        
        
    }
    
    
    func getCarInfoStr() -> String? {
        
        var str = ""
        
        for item in shopCartList {
            
            for subItem in item.goods {
                
                if subItem.isSelect == true {
                    str.append(subItem.cart_id)
                    str.append("|")
                    str.append(subItem.goods_num)
                    str.append(",")
                }
                
            }
            
        }
        
        if str.contains("|"){
            
            str.remove(at: str.index(str.endIndex, offsetBy: -1))
            
            return str
            
        }else{
            
            return nil
            
            
        }
        
    }

    
    
    func getCarInfoStr2() -> String? {
        
        var str = ""
        
        for item in shopCartList {
            
            for subItem in item.goods {
                
                if subItem.isSelect == true {
                    str.append(subItem.goods_id)
                    str.append("|")
                    str.append(subItem.goods_num)
                    str.append(",")
                }
                
            }
            
        }
        
        QL1(str)
        
        if str.contains("|"){
            
            str.remove(at: str.index(str.endIndex, offsetBy: -1))
            
            return str
            
        }else{
            
            return nil
            
            
        }
        
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    
       
    
  
}


// MARK:- UI相关
extension ShoppingCarController{




}


// MARK:- 数据请求
extension ShoppingCarController{


    func loadData() {
        
        SVProgressHUD.show(withStatus: "正在加载数据...")

        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_cart&a=cart_list", parameters: nil) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                SVProgressHUD.dismiss()
                
                self?.hotRecommList.removeAll()
                for dic in responseObject!["datas"]!["hot_recomm_list"] as! [[String : AnyObject]]{
                    
                    self?.hotRecommList.append(HomeItemModel(dic: dic))
                    
                }

                 self?.shopCartList.removeAll()
                if let temp = responseObject!["datas"]!["cart_list"] as? [[String : AnyObject]]{
                
                
                    for dic in temp{
                        
                        self?.shopCartList.append(ShopCartListModel(dic: dic))
                        
                    }

                
                }
                
                
                
                if self!.hotRecommList.count > 0{
                    
                    
                    if self!.shopCartList.count > 0{
                        
                        self!.bottomView.isHidden = false
                        
                        if self!.bottomView.frame.origin.y == KScreenH - 98{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 98, 0)
                            
                        }else{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0)
                        }
 
                        
                    }else{
                        
                        
                        self!.bottomView.isHidden = true
                        
                        if self!.bottomView.frame.origin.y == KScreenH - 98{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0)
                            
                        }else{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
                        }
                        
  
                        
                    }
                    
                
                
                }else{
                
                
                
                    if self!.shopCartList.count > 0{
 
                        self!.bottomView.isHidden = false
                        
                        if self!.bottomView.frame.origin.y == KScreenH - 98{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 98, 0)
                            
                        }else{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0)
                        }
  
                    }else{
                        
                    self!.nothingRootView.isHidden = false
  
                    self!.nothingRootView.bottomLabel.attributedText = self!.attributedString(str: "亲!您的购物车还是\n空的哟~", font: UIFont.systemFont(ofSize: 15))
                        
                        self!.bottomView.isHidden = true
                        
                        if self!.bottomView.frame.origin.y == KScreenH - 98{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0)
                            
                        }else{
                            
                            self!.plainTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
                        }
                        

 
                        
                        
                    }

                
                
                }
                
            
                self!.calculateTotalPrice()
               
                self!.plainTableView.reloadData()
                

                
                if self!.shopCartList.count > 0{
                
                    self!.plainTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
                    
                
                }
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
            
        }
        
        
    }





}




extension ShoppingCarController{


    override func numberOfSections(in tableView: UITableView) -> Int {
        
        
        if hotRecommList.count > 0 {
            if shopCartList.count > 0 {
                return shopCartList.count + 1
            } else {
                return 2
            }
            
        } else {
            
            if shopCartList.count > 0 {
                return shopCartList.count
            } else {
                return 0
            }
            
        }
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      
        if hotRecommList.count > 0 {
            if shopCartList.count > 0 {
                if section == shopCartList.count {
                    return likeItems.count
                } else {
                    return shopCartList[section].goods.count
                }
                
            } else {
                
                if section == 0 {
                    return 1
                } else {
                    return likeItems.count
                }
                
            }
            
        } else {
            
            if shopCartList.count > 0 {
                
                return shopCartList[section].goods.count
                
            } else {
                
                return 0
            }
            
        }
    }
    
    
//goods_image  goods_name   "¥" + model1.goods_price
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        var tableCell : UITableViewCell? = nil
        

        if hotRecommList.count > 0 {
            if shopCartList.count > 0 {
                if indexPath.section == shopCartList.count {
                    let tempCell : HomeYouLikeCell =  tableView.dequeueReusableCell(withIdentifier: HomeYouLikeCell.identifer()) as! HomeYouLikeCell
                    
                    tempCell.likeItems = likeItems[indexPath.row]
                    
                    tableCell = tempCell
                } else {
                    let tempCell : ShoppingCarCell =  tableView.dequeueReusableCell(withIdentifier: ShoppingCarCell.identifer()) as! ShoppingCarCell
                    
                    tempCell.delegate = self
                    
                    if indexPath.row == shopCartList[indexPath.section].goods.count - 1 {
                        
                        tempCell.isLastRow = true
                    }else{
                        tempCell.isLastRow = false
                        
                        
                    }
                    
                    tempCell.index = indexPath
                    
                    tempCell.model = shopCartList[indexPath.section].goods[indexPath.row]
                    
                    tableCell = tempCell
                }
                
            } else {
                
                if indexPath.section == 0 {
                    let tempCell : ShoppingNotingCell =  tableView.dequeueReusableCell(withIdentifier: ShoppingNotingCell.identifer()) as! ShoppingNotingCell
                    
                    tableCell = tempCell
                } else {
                    let tempCell : HomeYouLikeCell =  tableView.dequeueReusableCell(withIdentifier: HomeYouLikeCell.identifer()) as! HomeYouLikeCell
                    
                    tempCell.likeItems = likeItems[indexPath.row]

                    
                    tableCell = tempCell
                }
                
            }
            
        } else {
            
            if shopCartList.count > 0 {
                
                let tempCell : ShoppingCarCell =  tableView.dequeueReusableCell(withIdentifier: ShoppingCarCell.identifer()) as! ShoppingCarCell
                
                tempCell.delegate = self

                if indexPath.row == shopCartList[indexPath.section].goods.count - 1 {
                    
                    tempCell.isLastRow = true
                }else{
                    tempCell.isLastRow = false
                    
                    
                }

                
                tempCell.index = indexPath
                
                tempCell.model = shopCartList[indexPath.section].goods[indexPath.row]

                tableCell = tempCell
                
            } else {
                
                let tempCell : BaseTableViewCell =  tableView.dequeueReusableCell(withIdentifier: BaseTableViewCell.identifer()) as! BaseTableViewCell
                
                tableCell = tempCell
            }
            
        }

        
        
        
        return tableCell!
        
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        let temp = tableView.cellForRow(at: indexPath)
//        
//        if temp is  ShoppingCarCell{
//            
//            let url = shopCartList[indexPath.section].goods[indexPath.row].detail_url
//            
//            let temp = GoodsDetailController()
//            
//            temp.urlStr = url
//            
//            navigationController?.pushViewController(temp, animated: true)
//        }
//        
        
        
    }
    
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if hotRecommList.count > 0 {
            if shopCartList.count > 0 {
                
                return 44
         
            } else {
                if section == 0 {
                    return 0
                } else {
                    return 44
                }
            }
            
        } else {
            
            if shopCartList.count > 0 {
                return 44
            } else {
                return 0
            }
            
        }
 
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if hotRecommList.count > 0 {
            if shopCartList.count > 0 {
                if section == shopCartList.count {
                    let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: ShoppingCarHeaderTwo.identifer()) as! ShoppingCarHeaderTwo
                    
                    return temp
                    
                } else {
                    
                    
                    let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: ShoppingCarHeaderOne.identifer()) as! ShoppingCarHeaderOne
                    
                    temp.delegate = self
                    
                    temp.model = shopCartList[section]
                    
                    
                    return temp
                    
                }
            } else {
                if section == 0 {
                    return UIView()
                } else {
                    let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: ShoppingCarHeaderTwo.identifer()) as! ShoppingCarHeaderTwo
                    
                    return temp
                }
            }
            
        } else {
            
            if shopCartList.count > 0 {
                let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: ShoppingCarHeaderOne.identifer()) as! ShoppingCarHeaderOne
                
                temp.delegate = self
                
                temp.model = shopCartList[section]

                return temp
                
            } else {
                
                return UIView()
            }
            
        }
    }
    
    
    
    
    
    


}

extension ShoppingCarController : ShoppingCarCellDelegate{

    func calculateTotalPrice() {
        
        var totalPrice : Float = 0.0
        var goodsCount : Int = 0
        var isAllSelect = true
        
        for item in shopCartList {
            
            item.isSelect = true
            
            for subItem in item.goods {
                let oneGoodCount = Int(subItem.goods_num)!
                let oneGoodPrice = Float(subItem.goods_price)!
                
                if subItem.isSelect == true {
                    totalPrice += (oneGoodPrice * Float(oneGoodCount))
                    goodsCount += oneGoodCount
                } else {
                    
                    item.isSelect = false
                    
                    isAllSelect = false
                    
                }
            }
            
            
        }
        
 
        
        bottomView.sumLabel.text = "¥\(totalPrice)"
        
        bottomView.payBtn.setTitle("付款(\(goodsCount))", for: .normal)
        
        bottomView.leftSelectBtn.isSelected = isAllSelect
        
        
    }


}



